package cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.ProxyRefDispatcher;

public class TestProxyRefDispatcher {

	interface Foo {
		String foo();
	}

	interface Bar {
		String bar();
	}

	final static Object[] impls = new Object[] { new Foo() {
		public String foo() {
			return "foo1";
		}
	}, new Bar() {
		public String bar() {
			return "bar1";
		}
	} };

	final static Object[] proxyReference = new Object[1];

	private static Object create() {
		Callback[] callbacks = new Callback[] { new ProxyRefDispatcher() {
			public Object loadObject(Object proxy) {
				proxyReference[0] = proxy;
				return impls[0];
			}
		}, new ProxyRefDispatcher() {
			public Object loadObject(Object proxy) {
				proxyReference[0] = proxy;
				return impls[1];
			}
		} };
		
		Enhancer e = new Enhancer();
        e.setInterfaces(new Class[]{ Foo.class, Bar.class });
        e.setCallbacks(callbacks);
        e.setCallbackFilter(new CallbackFilter() {
            public int accept(Method method) {
                return (method.getDeclaringClass().equals(Foo.class)) ? 0 : 1;
            }
        });
        return e.create();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(proxyReference[0]);
		Foo obj = (Foo)create();
		System.out.println(obj.foo().equals("foo1"));
		System.out.println(obj);
		System.out.println(proxyReference[0]);
	}

}
